<?php

/**
 * @author luoshumai
 * 大拇哥供应商
 */

namespace App\Service\OrderService\OrderRouteService;

use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\VendorClient\ShopdamugeApi\ShopdamugeApiClient;
use App\Service\OrderService\BaseSupplierRouterService;


class Shopdamuge extends BaseSupplierRouterService
{
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder($param = [])
    {
        //下单商品重组
        $supplierGoodsInfo  = $param['supplierGoodsInfo'];
        $userGoodsList      = $supplierGoodsInfo['userGoodsList'];
        $goodsList          = $supplierGoodsInfo['goodsList'];
        $supplierCode       = $supplierGoodsInfo['supplierCode'];
        $currentGoods       = current($goodsList);
        $supplierCommodityType = $currentGoods['supplierCommodityType'];

        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
        ) ? true : false;
        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;

        $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
        $param['order']['supplier_csn'] = IdService::instance()->getOtherID();
        if( $isDelare && !$isShop && $supplierCommodityType != GOODS_TYPE_YBMY ) {
            $param['order']['supplier_dsn'] = (string)$param['order']['orderSn'];
        } else {
            $param['order']['supplier_dsn'] = (string)IdService::instance()->getOtherID();
        }
        $param['order']['isQueryExpress'] = 1;
        $res = OrderSupplier::instance()->getSupplierCreateOrderData($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }

        $orderItems[] = $res['data'];
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'supplierCode' => $supplierCode,
            'orderItems' => $orderItems
        ]);
    }

    /**
     * 订单申报
     * @param array $param
     * @return mixed
     */
    public function orderPay($param = [])
    {
        return $this->callSdkApi(ShopdamugeApiClient::class,$param['apiBody'])->createOrder($param);
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel($param = [])
    {
        return Normal::returnCode(Normal::SUC, "获取成功");
    }

    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale($param = [])
    {
        return $this->callSdkApi(ShopdamugeApiClient::class,$param['apiBody'])->cancelOrder($param);
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function orderExpress($param = [])
    {
        return Normal::returnCode(Normal::SUC, "处理完成");
    }

    /**
     * 商品列表查询接口
     * @param array $param
     * @return mixed
     */
    public function queryGoodsList( $param = [] )
    {
        $res = $this->callSdkApi(ShopdamugeApiClient::class,$param['apiBody'])->{__FUNCTION__}($param['queryBody']);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'total' => count($res['data']['data']),
            'list'  => $res['data']['data']
        ]);
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }

        $res = $this->callSdkApi(ShopdamugeApiClient::class,$apiBody)->{__FUNCTION__}($orderInfo);
        if( $res['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }
        
        $logistics=$res['data'];
        //订单状态(-2：废弃（仓库的废弃单）/ -1：问题单/ 0：清关申报中 /4：清关查验（清关状态：查验）/1：清关通过 （清关状态：放行）/ 3：清关失败（清关状态：海关退单）/ 2：出库) 
        if( in_array($logistics['orderstatus'],[-2,-1,3]) ) {
            //这里要修改状态
            OrderSupplier::instance()
                ->where(['id'=>$orderID,'company_id'=>$queryBody['supplierID']])
                ->update([
                    'is_query_express'=>0,
                    'order_decalre_status'=>2,//申报失败
                    'order_decalre_result'=>$logistics['orderstatusdesc']??'申报失败'
                ]);
            return Normal::returnCode(Normal::FAIL,'申报失败');
        }
        //放行和出库
        if (in_array($logistics['orderstatus'],[1,2])){
            return  Normal::returnCode(Normal::SUC,"已发货",[
                'expressInfo' => [
                    'express_name'  => $apiBody['expressid'],
                    'express_sn'    => $logistics['logisticsno'],
                ]
            ]);
        }
        return Normal::returnCode(Normal::FAIL,'还未发货');
    }
}
